<template>
  <div class="modal-overlay" @click="closeModal">
    <div class="trade-modal" @click.stop>
      <div class="modal-header">
        <h3>{{ getResourceName(resource) }} 交易</h3>
        <button class="close-btn" @click="closeModal">✕</button>
      </div>
      
      <div class="modal-content">
        <div class="resource-info">
          <div class="resource-icon">{{ getResourceIcon(resource) }}</div>
          <div class="resource-details">
            <div class="current-amount">
              当前拥有: {{ formatNumber(currentAmount) }}
            </div>
            <div class="market-prices">
              <span class="buy-price">买入价: {{ buyPrice }}</span>
              <span class="sell-price">卖出价: {{ sellPrice }}</span>
            </div>
          </div>
        </div>
        
        <div class="trade-controls">
          <div class="trade-type-selector">
            <button 
              class="type-btn"
              :class="{ active: tradeType === 'buy' }"
              @click="tradeType = 'buy'"
            >
              买入
            </button>
            <button 
              class="type-btn"
              :class="{ active: tradeType === 'sell' }"
              @click="tradeType = 'sell'"
            >
              卖出
            </button>
          </div>
          
          <div class="amount-input">
            <label>数量:</label>
            <div class="input-group">
              <button class="amount-btn" @click="adjustAmount(-100)">-100</button>
              <button class="amount-btn" @click="adjustAmount(-10)">-10</button>
              <input 
                v-model.number="tradeAmount" 
                type="number" 
                min="0" 
                :max="maxAmount"
                class="amount-field"
              />
              <button class="amount-btn" @click="adjustAmount(10)">+10</button>
              <button class="amount-btn" @click="adjustAmount(100)">+100</button>
            </div>
            <div class="quick-amounts">
              <button 
                v-for="percent in [25, 50, 75, 100]" 
                :key="percent"
                class="quick-btn"
                @click="setPercentAmount(percent)"
              >
                {{ percent }}%
              </button>
            </div>
          </div>
          
          <div class="trade-summary">
            <div class="summary-row">
              <span>{{ tradeType === 'buy' ? '购买数量' : '出售数量' }}:</span>
              <span class="highlight">{{ formatNumber(tradeAmount) }}</span>
            </div>
            <div class="summary-row">
              <span>{{ tradeType === 'buy' ? '总花费' : '总收入' }}:</span>
              <span class="highlight">{{ formatNumber(totalCost) }} 信用点</span>
            </div>
            <div class="summary-row">
              <span>交易后余额:</span>
              <span :class="getBalanceClass()">
                {{ formatNumber(afterTradeBalance) }}
              </span>
            </div>
          </div>
        </div>
      </div>
      
      <div class="modal-footer">
        <button class="cancel-btn" @click="closeModal">
          取消
        </button>
        <button 
          class="confirm-btn"
          :disabled="!canTrade"
          @click="executeTrade"
        >
          确认{{ tradeType === 'buy' ? '购买' : '出售' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { useResourcesStore } from '@/stores'

interface Props {
  resource: string
}

interface Emits {
  (e: 'close'): void
  (e: 'trade', data: { resource: string; amount: number; type: 'buy' | 'sell' }): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const resourcesStore = useResourcesStore()

const tradeType = ref<'buy' | 'sell'>('buy')
const tradeAmount = ref(100)

const currentAmount = computed(() => {
  return resourcesStore.resources[props.resource] || 0
})

const currentCredits = computed(() => {
  return resourcesStore.resources.credits || 0
})

const buyPrice = computed(() => {
  return resourcesStore.getMarketPrice(props.resource, 'buy')
})

const sellPrice = computed(() => {
  return resourcesStore.getMarketPrice(props.resource, 'sell')
})

const currentPrice = computed(() => {
  return tradeType.value === 'buy' ? buyPrice.value : sellPrice.value
})

const totalCost = computed(() => {
  return tradeAmount.value * currentPrice.value
})

const maxAmount = computed(() => {
  if (tradeType.value === 'buy') {
    return Math.floor(currentCredits.value / buyPrice.value)
  } else {
    return currentAmount.value
  }
})

const afterTradeBalance = computed(() => {
  if (tradeType.value === 'buy') {
    return currentCredits.value - totalCost.value
  } else {
    return currentCredits.value + totalCost.value
  }
})

const canTrade = computed(() => {
  if (tradeAmount.value <= 0) return false
  if (tradeAmount.value > maxAmount.value) return false
  if (tradeType.value === 'buy' && totalCost.value > currentCredits.value) return false
  if (tradeType.value === 'sell' && tradeAmount.value > currentAmount.value) return false
  return true
})

function getResourceName(resourceId: string): string {
  const names: Record<string, string> = {
    energy: '能量',
    metals: '金属',
    crystals: '水晶',
    rare_metals: '稀有金属',
    credits: '信用点',
    research_points: '研究点',
    influence: '影响力'
  }
  return names[resourceId] || resourceId
}

function getResourceIcon(resourceId: string): string {
  const icons: Record<string, string> = {
    energy: '⚡',
    metals: '🔩',
    crystals: '💎',
    rare_metals: '🌟',
    credits: '💰',
    research_points: '🔬',
    influence: '👑'
  }
  return icons[resourceId] || '❓'
}

function formatNumber(num: number): string {
  if (num >= 1000000000) {
    return (num / 1000000000).toFixed(1) + 'B'
  } else if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + 'M'
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'K'
  } else {
    return Math.floor(num).toString()
  }
}

function adjustAmount(delta: number) {
  const newAmount = Math.max(0, Math.min(maxAmount.value, tradeAmount.value + delta))
  tradeAmount.value = newAmount
}

function setPercentAmount(percent: number) {
  tradeAmount.value = Math.floor(maxAmount.value * percent / 100)
}

function getBalanceClass(): string {
  if (afterTradeBalance.value < 0) return 'negative'
  if (afterTradeBalance.value < currentCredits.value * 0.1) return 'warning'
  return 'positive'
}

function closeModal() {
  emit('close')
}

function executeTrade() {
  if (canTrade.value) {
    emit('trade', {
      resource: props.resource,
      amount: tradeAmount.value,
      type: tradeType.value
    })
  }
}
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(5px);
}

.trade-modal {
  background: rgba(20, 20, 30, 0.95);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  backdrop-filter: blur(10px);
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.5);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.modal-header h3 {
  margin: 0;
  color: #ffffff;
  font-size: 1.25rem;
}

.close-btn {
  width: 32px;
  height: 32px;
  background: rgba(255, 255, 255, 0.1);
  border: none;
  border-radius: 6px;
  color: #ffffff;
  font-size: 1.2rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background: rgba(255, 68, 68, 0.3);
  color: #ff4444;
}

.modal-content {
  padding: 1.5rem;
}

.resource-info {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 8px;
  margin-bottom: 1.5rem;
}

.resource-icon {
  font-size: 2.5rem;
}

.resource-details {
  flex: 1;
}

.current-amount {
  font-size: 1.1rem;
  font-weight: 600;
  color: #ffffff;
  margin-bottom: 0.5rem;
}

.market-prices {
  display: flex;
  gap: 1rem;
  font-size: 0.9rem;
}

.buy-price {
  color: #00ff88;
}

.sell-price {
  color: #ff4444;
}

.trade-controls {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.trade-type-selector {
  display: flex;
  gap: 0.5rem;
}

.type-btn {
  flex: 1;
  padding: 0.75rem;
  background: rgba(255, 255, 255, 0.1);
  color: #cccccc;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 6px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.type-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.type-btn.active {
  background: #00d4ff;
  color: #000000;
  border-color: #00d4ff;
}

.amount-input label {
  display: block;
  margin-bottom: 0.5rem;
  color: #cccccc;
  font-weight: 500;
}

.input-group {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 0.75rem;
}

.amount-btn {
  padding: 0.5rem 0.75rem;
  background: rgba(255, 255, 255, 0.1);
  color: #ffffff;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 4px;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.amount-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.amount-field {
  flex: 1;
  padding: 0.75rem;
  background: rgba(0, 0, 0, 0.3);
  color: #ffffff;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 6px;
  font-size: 1rem;
  text-align: center;
}

.amount-field:focus {
  outline: none;
  border-color: #00d4ff;
  box-shadow: 0 0 0 2px rgba(0, 212, 255, 0.2);
}

.quick-amounts {
  display: flex;
  gap: 0.5rem;
}

.quick-btn {
  flex: 1;
  padding: 0.5rem;
  background: rgba(0, 212, 255, 0.2);
  color: #00d4ff;
  border: 1px solid #00d4ff;
  border-radius: 4px;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.quick-btn:hover {
  background: #00d4ff;
  color: #000000;
}

.trade-summary {
  background: rgba(0, 0, 0, 0.3);
  border-radius: 8px;
  padding: 1rem;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
  color: #cccccc;
}

.summary-row:last-child {
  margin-bottom: 0;
  padding-top: 0.5rem;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.highlight {
  color: #ffffff;
  font-weight: 600;
}

.positive {
  color: #00ff88;
}

.negative {
  color: #ff4444;
}

.warning {
  color: #f59e0b;
}

.modal-footer {
  display: flex;
  gap: 1rem;
  padding: 1.5rem;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.cancel-btn,
.confirm-btn {
  flex: 1;
  padding: 0.75rem;
  border: none;
  border-radius: 6px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.cancel-btn {
  background: rgba(255, 255, 255, 0.1);
  color: #cccccc;
}

.cancel-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.confirm-btn {
  background: #00d4ff;
  color: #000000;
}

.confirm-btn:hover:not(:disabled) {
  background: #0099cc;
  transform: translateY(-1px);
}

.confirm-btn:disabled {
  background: rgba(255, 255, 255, 0.1);
  color: #666666;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .trade-modal {
    width: 95%;
    margin: 1rem;
  }
  
  .modal-header,
  .modal-content,
  .modal-footer {
    padding: 1rem;
  }
  
  .resource-info {
    flex-direction: column;
    text-align: center;
    gap: 0.75rem;
  }
  
  .market-prices {
    justify-content: center;
  }
  
  .input-group {
    flex-wrap: wrap;
  }
  
  .amount-field {
    min-width: 120px;
  }
}
</style>